package com.hcloud.auth.third;

import com.hcloud.auth.service.ThirdUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * 短信登录配置
 * @author hepangui
 * @date 2018-12-12
 */

@Component
public class ThirdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler hcloudAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler hcloudAuthenticationFailureHandler;

    @Autowired
    private ThirdUserService thirdUserService;

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        //配置Filter
        var thirdAuthenticationFilter = new ThirdAuthenticationFilter();
        //配置AuthenticationManager
        thirdAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        //配置
        thirdAuthenticationFilter.setAuthenticationSuccessHandler(hcloudAuthenticationSuccessHandler);
        thirdAuthenticationFilter.setAuthenticationFailureHandler(hcloudAuthenticationFailureHandler);
        ThirdAuthenticationProvider thirdAuthenticationProvider = new ThirdAuthenticationProvider(thirdUserService);
        //将自定义的AuthenticationProvider添加到AuthenticationManager所管理的Provider集合里面去
        builder.authenticationProvider(thirdAuthenticationProvider)
                //将过滤器添加到用户名密码验证过滤器的后面就行
                .addFilterAfter(thirdAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
